package com.ss.android.article.base.feature.category.a;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.os.AsyncTask;
import android.os.Looper;
import android.os.Message;

import com.bytedance.article.common.c.TTUtils;
import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.UIUtils;
import com.bytedance.common.utility.b.ThreadPlus;
import com.bytedance.common.utility.c.SharedPreferenceCompat;
import com.bytedance.common.utility.collection.WeakHandler;
import com.bytedance.common.utility.collection.WeakList;
import com.ss.android.article.base.app.AppData;
import com.ss.android.article.base.feature.app.a.ArticleConstants;
import com.ss.android.article.base.feature.model.CategoryItem;
import com.ss.android.article.base.utils.a.SharedPreferenceUtils;
import com.ss.android.common.AbsApiThread;
import com.ss.android.common.applog.AppLog;
import com.ss.android.common.lib.MobClickCombiner;
import com.ss.android.common.location.LocationHelper;
import com.ss.android.common.util.NetworkUtils;
import com.ss.android.http.legacy.a.NameValueImpl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public final class CategoryManager implements WeakHandler.Callback {
    public interface a$a {
        void c(boolean arg1);
    }

    static final class b {
        public Map a = new LinkedHashMap();
        public List b = new ArrayList();
        public String c;
    }

    public final class c {
        public final int a;
        public final Map b = new LinkedHashMap();
        public String c;
        public String d;
        public long e;

        public c(int arg2) {
            this.a = arg2;
        }
    }

    final class d extends AsyncTask {
        private String a;

        public d(Integer arg2) {
            this.a = CategoryManager.a(arg2.intValue());
        }

        protected final Object doInBackground(Object[] arg6) {
            Object v4 = null;
            if (!android.support.design.a.isTextEmpty(this.a) && arg6 != null && arg6.length > 0) {
                Object v0 = arg6[0];
                if (v0 != null) {
                    SharedPreferenceUtils.inst();
                    SharedPreferences.Editor editor = SharedPreferenceUtils.getEditor("category");
                    editor.putString(SharedPreferenceUtils.getMigrateKey("category", this.a), ((String) v0));
                    SharedPreferenceCompat.commit(editor);
                }
            }
            return v4;
        }
    }

    public final Map a = new LinkedHashMap();
    public final Context mContext;
    public final Map c = new LinkedHashMap();
    public CategoryItem mRecommendCategoryItem;
    public WeakList mHomePageList = new WeakList();
    WeakHandler mWeakHandler = new WeakHandler(Looper.getMainLooper(), this);
    private static CategoryManager instance = null;
    private Map h = new LinkedHashMap();
    private final Map i = new LinkedHashMap();
    private final Map<String, CategoryItem> mCategoryItemMap = new LinkedHashMap();
    private AppData k = AppData.getInstance();
    private String l;
    private boolean m = false;
    private boolean n = false;
    private long o = 0;
    private long p = 0;
    private int q = 0;
    private boolean r = true;

    private CategoryManager(Context context) {
        this.mContext = context.getApplicationContext();
        this.mRecommendCategoryItem = new CategoryItem("__all__", context.getString(com.ss.android.article.browser.R.string.category_all), "6286225228934679042");
        this.h.put("__all__", this.mRecommendCategoryItem);
        this.c.put("video", new CategoryItem("video", this.mContext.getString(com.ss.android.article.browser.R.string.category_video)));
        this.h.putAll(this.c);
        this.c.put("news_hot", new CategoryItem("news_hot", this.mContext.getString(com.ss.android.article.browser.R.string.category_hot)));
        this.c.put("news_local", new CategoryItem("news_local", "本地"));
        this.c.put("news_society", new CategoryItem("news_society", this.mContext.getString(com.ss.android.article.browser.R.string.category_society), "6215497899397089794"));
        this.c.put("news_entertainment", new CategoryItem("news_entertainment", this.mContext.getString(com.ss.android.article.browser.R.string.category_entertainment), "6215497896830175745"));
        this.c.put("组图", new CategoryItem("组图", this.mContext.getString(com.ss.android.article.browser.R.string.picture)));
        this.c.put("news_car", new CategoryItem("news_car", this.mContext.getString(com.ss.android.article.browser.R.string.category_car), "6215497898671475202"));
        this.c.put("news_sports", new CategoryItem("news_sports", this.mContext.getString(com.ss.android.article.browser.R.string.category_sports), "6215497726554016258"));
        this.i.putAll(this.c);
        SharedPreferenceUtils.inst();
        SharedPreferenceUtils.getString("category", "category_version", "0");
        this.e();
    }

    public final CategoryItem getCategoryItem(String category) {
        if (this.mRecommendCategoryItem.category.equals(category)) {
            return this.mRecommendCategoryItem;
        } else {
            return this.mCategoryItemMap.get(category);
        }
    }

    public static CategoryManager getInstance(Context context) {
        synchronized (CategoryManager.class) {
            if (CategoryManager.instance == null) {
                CategoryManager.instance = new CategoryManager(context);
            }
        }
        return CategoryManager.instance;
    }

    public final void a() {
        if (!android.support.design.a.isTextEmpty(AppLog.deviceId())) {
            long v4 = System.currentTimeMillis();
            long v0 = this.r ? 3600000 : 7200000;
            this.r = false;
            long v2 = (((long) AppData.getInstance().mLiteCategoryRefresh)) * 1000L;
            if (v2 > 0) {
                v0 = v2;
            }

            if (Logger.debug()) {
                Logger.d("CategoryManager", "interval=" + v0 / 1000L);
            }

            if (v4 - this.o < v0) {
                if (!Logger.debug()) {
                    return;
                }
                Logger.d("CategoryManager", "do not refresh category now. count down " + (v0 - v4 + this.o) / 1000L + "s.");
                return;
            }

            if (Logger.debug()) {
                Logger.d("CategoryManager", "more " + (v4 - this.o - v0) / 1000L + "s.");
            }

            if (v4 - this.p < 30000) {
                return;
            }

            if (!NetworkUtils.isNetworkAvailable(this.mContext) && (this.m)) {
                return;
            }

            if (!this.m) {
                this.e();
                return;
            }

            this.d();
        }
    }

    static String a(int arg1) {
        String v0 = null;
        switch (arg1) {
            case 0: {
                v0 = "category_list_v2";
                break;
            }
            case 1: {
                v0 = "subscribe_list";
                break;
            }
        }

        return v0;
    }

    public static String list2Str(Collection collection) {
        try {
            JSONArray jsonArray = new JSONArray();
            if (collection != null) {
                Iterator iterator = collection.iterator();
                while (iterator.hasNext()) {
                    jsonArray.put(iterator.next());
                }
            }
            return jsonArray.toString();
        } catch (Exception e) {
            Logger.w("CategoryManager", "exception in list2Str: " + e.toString());
            return "";
        }
    }

    private static JSONObject toJO(CategoryItem categoryItem) {
        if (categoryItem == null) {
            return null;
        }

        try {
            JSONObject jo = new JSONObject();
            jo.put("category", categoryItem.category);
            jo.put("category_id", categoryItem.categoryId);
            jo.put("concern_id", categoryItem.concernId);
            jo.put("default_add", categoryItem.defaultAdd);
            jo.put("description", categoryItem.description);
            jo.put("flags", categoryItem.flags);
            jo.put("icon_url", categoryItem.iconUrl);
            jo.put("name", categoryItem.name);
            jo.put("tip_new", categoryItem.tip_new);
            jo.put("type", categoryItem.type);
            jo.put("web_url", categoryItem.webUrl);
            jo.put("url", null);
            return jo;
        } catch (Exception e) {
        }

        return null;
    }

    private void a(b arg5) {
        if (arg5 != null) {
            if (arg5.a != null && !arg5.a.isEmpty()) {
                this.l = arg5.c;
                Iterator v1 = arg5.a.values().iterator();
                while (v1.hasNext()) {
                    Object v0 = v1.next();
                    if (!arg5.b.contains(((CategoryItem) v0).category)) {
                        continue;
                    }

                    ((CategoryItem) v0).tip_new = false;
                }

                this.mCategoryItemMap.clear();
                this.mCategoryItemMap.putAll(arg5.a);
                if (arg5.b == null) {
                } else if (!arg5.b.isEmpty()) {
                    this.c(arg5.b);
                } else {
                }

                return;
            }

            this.mCategoryItemMap.putAll(this.c);
            this.a(this.i);
            this.l = "0";
        }
    }

    private void a(Map arg5) {
        if (arg5 != null && !arg5.isEmpty()) {
            if (this.mRecommendCategoryItem == null) {
                this.mRecommendCategoryItem = new CategoryItem("__all__", this.mContext.getString(com.ss.android.article.browser.R.string.category_all));
            }

            this.a.clear();
            this.a.put(this.mRecommendCategoryItem.category, this.mRecommendCategoryItem);
            this.a.putAll(arg5);
        }
    }

    private static void str2list(String arg5, List result) {
        int v0_1;
        if (android.support.design.a.isTextEmpty(arg5)) {
            return;
        }

        if (result == null) {
            return;
        }

        try {
            JSONArray v1 = new JSONArray(arg5);
            int v2 = v1.length();
            v0_1 = 0;
            while (true) {
                if (v0_1 >= v2) {
                    return;
                }
                String v3 = v1.getString(v0_1);
                if (!android.support.design.a.isTextEmpty(v3)) {
                    result.add(v3);
                }
                ++v0_1;
                continue;
            }
        } catch (Exception v0) {
            Logger.w("CategoryManager", "exception in str2list: " + v0.toString());
        }
    }

    public static void a(Map arg13, JSONArray arg14, boolean arg15) throws JSONException {
        int v1_1;
        if (arg13 != null && arg14 != null) {
            int v10 = arg14.length();
            if (v10 > 0) {
                arg13.clear();
                ArrayList v11 = new ArrayList();
                int v9;
                for (v9 = 0; v9 < v10; ++v9) {
                    JSONObject v12 = arg14.optJSONObject(v9);
                    if (v12 != null) {
                        String category = v12.optString("category");
                        String categoryId = v12.optString("category_id");
                        String concernId = v12.optString("concern_id");
                        String name = v12.optString("name");
                        if (!android.support.design.a.isTextEmpty(category)
                                && !android.support.design.a.isTextEmpty(name)
                                && !((List) v11).contains(category)) {
                            ((List) v11).add(category);
                            String description = v12.optString("description");
                            String iconUrl = v12.optString("icon_url");
                            int type = v12.optInt("type");
                            String webUrl = v12.optString("web_url", null);
                            CategoryItem categoryItem = new CategoryItem(categoryId, concernId, type, category, name, description, iconUrl, webUrl);
                            categoryItem.flags = v12.optInt("flags");
                            if (!android.support.design.a.isTextEmpty(categoryItem.category)) {
                                switch (categoryItem.type) {
                                    case 1: {
                                        v1_1 = 1;
                                        break;
                                    }
                                    case 3: {
                                        v1_1 = 1;
                                        break;
                                    }
                                    case 4: {
                                        v1_1 = 1;
                                        break;
                                    }
                                    case 5: {
                                        if (!android.support.design.a.isTextEmpty(categoryItem.webUrl)) {
                                            v1_1 = 1;
                                        } else {
                                            v1_1 = 0;
                                        }
                                        break;
                                    }
                                    case 6: {
                                        v1_1 = 1;
                                        break;
                                    }
                                    default:
                                        v1_1 = 0;
                                        break;
                                }
                            } else {
                                v1_1 = 0;
                            }

                            if (v1_1 == 0) {
                                Logger.w("CategoryManager", "invalid category_item: " + type + " " + category + " " + webUrl);
                                continue;
                            }

                            arg13.put(category, categoryItem);
                            if (arg15) {
                                categoryItem.tip_new = AbsApiThread.optBoolean(v12, "tip_new", true);
                            }
                            categoryItem.defaultAdd = AbsApiThread.optBoolean(v12, "default_add", false);
                        }
                    }
                }
            }
        }
    }

    public final void a(boolean arg3) {
        Iterator v1 = this.mHomePageList.iterator();
        while (v1.hasNext()) {
            Object v0 = v1.next();
            if (v0 == null) {
                continue;
            }

            ((a$a) v0).c(arg3);
        }
    }

    private static JSONArray list2jarray(Collection<CategoryItem> categoryItems) {
        if (categoryItems != null && !categoryItems.isEmpty()) {
            JSONArray ja = new JSONArray();
            try {
                Iterator<CategoryItem> iterator = categoryItems.iterator();
                while (iterator.hasNext()) {
                    JSONObject jo = CategoryManager.toJO(iterator.next());
                    if (jo == null) {
                        continue;
                    }
                    ja.put(jo);
                }
            } catch (Exception e) {
                Logger.e("CategoryManager", "exception in list2jarray : " + e.toString());
            }
            return ja;
        } else {
            return null;
        }
    }

    final b b() {
        b v1 = new b();
        JSONArray ja = CategoryManager.list2jarray(this.c.values());
        String v0_1 = ja != null ? ja.toString() : null;
        String v2 = this.i.keySet().toString();
        SharedPreferenceUtils.inst();
        String v3 = SharedPreferenceUtils.getString("category", "category_list_v2", v0_1);
        SharedPreferenceUtils.inst();
        String v4 = SharedPreferenceUtils.getString("category", "subscribe_list", "");
        ja = new JSONArray();
        ja.put("__all__");
        ja.put("news_hot");
        v0_1 = "0";
        if (this.k.lastVersionCode <= 0) {
            v0_1 = "2";
        } else if (this.k.lastVersionCode != this.k.cD) {
            v0_1 = "1";
        }

        SharedPreferenceUtils.inst();
        v1.c = SharedPreferenceUtils.getString("category", "category_version", v0_1);
        if (!android.support.design.a.isTextEmpty(v3)) {
            try {
                CategoryManager.a(v1.a, new JSONArray(v3), false);
            } catch (Exception v0_2) {
                Logger.e("CategoryManager", "exception in loadLocalData : " + v0_2.toString());
            }
        }

        CategoryManager.str2list(v4, v1.b);
        if (v1.b.isEmpty()) {
            CategoryManager.str2list(v2, v1.b);
            v1.c = "0";
        }

        if (v1.b != null && v1.b.size() == 1) {
            MobClickCombiner.onEvent(this.mContext, "category", "pref_read_empty");
        }

        return v1;
    }

    private void c(Collection collection) {
        if (collection != null) {
            LinkedHashMap map = new LinkedHashMap();
            Iterator v2 = collection.iterator();
            while (v2.hasNext()) {
                Object v0 = v2.next();
                if (this.mCategoryItemMap.containsKey(v0)) {
                    map.put(v0, this.mCategoryItemMap.get(v0));
                } else {
                    if (!this.mRecommendCategoryItem.category.equals(v0)) {
                        continue;
                    }

                    map.put(v0, this.mRecommendCategoryItem);
                }
            }

            this.a(map);
            Set v0_1 = this.a.keySet();
            if (v0_1 != null) {
                if (((Collection) v0_1).size() == 1) {
                    MobClickCombiner.onEvent(this.mContext, "category", "pref_save_empty");
                    UIUtils.a(this.mContext, this.mContext.getResources().getString(com.ss.android.article.browser.R.string.category_null_error));
                }
                new d(Integer.valueOf(1))
                        .execute(new Object[]{CategoryManager.list2Str(v0_1)});
            }
        }
    }

    private void c() {
        this.a(false);
    }

    private void d() {
        ++this.q;
        final c v0 = new c(this.q);
        v0.d = this.k.localCityName;
        v0.c = this.l;
        v0.b.putAll(this.a);
        if (NetworkUtils.isNetworkAvailable(this.mContext)) {
            this.p = System.currentTimeMillis();
        }
        new ThreadPlus(
                new Runnable() {

                    public final void run() {
                        Message v0_7;
                        long v10 = 0;
                        CategoryManager v2 = CategoryManager.this;
                        CategoryManager.c v3 = v0;
                        try {
                            String v4 = ArticleConstants.categoryGetLightUrl;
                            ArrayList v5 = new ArrayList();
                            LocationHelper v0_1 = LocationHelper.getInstance(v2.mContext);
                            Address v1 = v0_1.loadSavedLocation();
                            if (v1 != null && (v1.hasLatitude()) && (v1.hasLongitude())) {
                                String v6 = v1.getLocality();
                                if (!android.support.design.a.isTextEmpty(v6)) {
                                    v5.add(new NameValueImpl("city", v6));
                                }

                                v5.add(new NameValueImpl("latitude", String.valueOf(v1.getLatitude())));
                                v5.add(new NameValueImpl("longitude", String.valueOf(v1.getLongitude())));
                                long v0_2 = v0_1.getLocTime();
                                if (v0_2 > v10) {
                                    v0_2 /= 1000;
                                }

                                if (v0_2 > v10) {
                                    v5.add(new NameValueImpl("loc_time", String.valueOf(v0_2)));
                                }
                            }

                            if (!android.support.design.a.isTextEmpty(v3.d)) {
                                v5.add(new NameValueImpl("user_city", v3.d));
                            }

                            Set v0_3 = v3.b.keySet();
                            ((Collection) v0_3).remove(v2.mRecommendCategoryItem.category);
                            if (((Collection) v0_3).isEmpty()) {
                                MobClickCombiner.onEvent(v2.mContext, "category", "sync_param_empty");
                            }

                            String v1_1 = CategoryManager.list2Str(((Collection) v0_3));
                            if ((android.support.design.a.isTextEmpty(v1_1)) && (android.support.design.a.isTextEmpty(v3.c)) || (((Collection) v0_3).isEmpty())) {
                                v3.c = "0";
                            }

                            v5.add(new NameValueImpl("categories", v1_1));
                            v5.add(new NameValueImpl("version", v3.c));
                            if (Logger.debug()) {
                                Logger.d("CategoryManager", "refresh category now.");
                            }

                            String v0_4 = NetworkUtils.executePost(-1, v4, ((List) v5));
                            if (!android.support.design.a.isTextEmpty(v0_4)) {
                                JSONObject v1_2 = new JSONObject(v0_4);
                                if (!"success".equals(v1_2.getString("message"))) {
                                    Logger.w("CategoryManager", "get category list error: " + v0_4);
                                } else {
                                    JSONObject v0_5 = v1_2.optJSONObject("data");
                                    if (v0_5 != null) {
                                        v3.e = System.currentTimeMillis();
                                        v3.c = v0_5.optString("version");
                                        JSONArray v0_6 = v0_5.optJSONArray("data");
                                        CategoryManager.a(v3.b, v0_6, true);
                                        SharedPreferenceUtils.inst();
                                        SharedPreferences.Editor v1_3 = SharedPreferenceUtils.getEditor("category");
                                        v1_3.putString(SharedPreferenceUtils.getMigrateKey("category", "category_list_v2"), v0_6.toString());
                                        v1_3.putString(SharedPreferenceUtils.getMigrateKey("category", "category_version"), v3.c);
                                        v1_3.putLong(SharedPreferenceUtils.getMigrateKey("category", "refresh_time_v2"), v3.e);
                                        SharedPreferenceCompat.commit(v1_3);
                                        v0_7 = v2.mWeakHandler.obtainMessage(10);
                                        v0_7.obj = v3;
                                        v2.mWeakHandler.sendMessage(v0_7);
                                        return;
                                    }
                                }
                            }
                        } catch (Throwable v0) {
                            TTUtils.getErrorCode(v2.mContext, v0);
                        }
                        v0_7 = v2.mWeakHandler.obtainMessage(11);
                        v0_7.obj = v3;
                        v2.mWeakHandler.sendMessage(v0_7);
                    }
                },
                "CategoryList-Thread",
                true).start();
    }

    private void e() {
        if (!this.m && !this.n) {
            this.n = true;
            new ThreadPlus(new Runnable() {

                public final void run() {
                    CategoryManager.b v1 = CategoryManager.this.b();
                    Message v2 = CategoryManager.this.mWeakHandler.obtainMessage(100);
                    v2.obj = v1;
                    CategoryManager.this.mWeakHandler.sendMessage(v2);
                }
            }, "Category-LoadLocalData-Thread", false).start();
        }
    }

    public final void handleMsg(Message message) {
        b v0_1;
        Object v0;
        int v1 = 0;
        switch (message.what) {
            case 10:
                v1 = 1;
            case 11: {
                if (!(message.obj instanceof c)) {
                    return;
                }
                v0 = message.obj;
                if (v0 != null && ((c) v0).a == this.q) {
                    this.o = ((c) v0).e;
                    if (v1 == 0) {
                        MobClickCombiner.onEvent(this.mContext, "category", "response_not_ok");
                    } else if (((c) v0).b.isEmpty()) {
                        MobClickCombiner.onEvent(this.mContext, "category", "response_empty");
                    } else {
                        ArrayList v3 = new ArrayList();
                        Iterator v4 = ((c) v0).b.values().iterator();
                        while (v4.hasNext()) {
                            Object v1_1 = v4.next();
                            if (!((CategoryItem) v1_1).defaultAdd) {
                                continue;
                            }
                            ((List) v3).add(((CategoryItem) v1_1).category);
                        }

                        if (((List) v3).isEmpty()) {
                            MobClickCombiner.onEvent(this.mContext, "category", "response_nothing_add");
                        }
                        if ((((List) v3).isEmpty()) && (this.a.isEmpty())) {
                            ((List) v3).addAll(this.i.keySet());
                        }
                        this.mCategoryItemMap.putAll(((c) v0).b);
                        this.l = ((c) v0).c;
                        this.c(v3);
                        this.a(true);
                    }
                    return;
                }
                MobClickCombiner.onEvent(this.mContext, "category", "query_invalid");
                break;
            }
            case 100: {
                if ((message.obj instanceof b)) {
                    v0_1 = (CategoryManager.b) message.obj;
                } else {
                    v0_1 = null;
                }
                this.a(v0_1);
                this.m = true;
                this.n = false;
                this.c();
                this.d();
                break;
            }
            case 101: {
                this.c();
                break;
            }
        }
    }
}

